package com.springboot.spring03tx.dao;

import com.springboot.spring03tx.bean.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
@Component
public class BookDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public Book getBookById(Integer id) {
        //1、查询图书SQL
        String sql = "select * from book where id  = ? ";
        //2、执行查询
        Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Book.class), id);
        return book;
    }
    //用于隔离级别测试
    @Transactional(isolation = Isolation.READ_UNCOMMITTED)
    public BigDecimal getBookPriceById(Integer id) {
        //1、查询图书SQL
        String sql = "select price from book where id  = ? ";
        //2、执行查询
        BigDecimal price = jdbcTemplate.queryForObject(sql, BigDecimal.class, id);
        return price;
    }

    // REPEATABLE_READ： 可重复读。 快照读。 MySQL默认
    // READ_COMMITTED： 读已提交。 当前读。 Oracle默认
    @Transactional(isolation = Isolation.REPEATABLE_READ)
    public BigDecimal getBookPrice(Integer id){
        String sql = "select price from book where id=?";
        BigDecimal decimal1 = jdbcTemplate.queryForObject(sql, BigDecimal.class, id);

        BigDecimal decimal2 = jdbcTemplate.queryForObject(sql, BigDecimal.class, id);

        BigDecimal decimal3 = jdbcTemplate.queryForObject(sql, BigDecimal.class, id);

        BigDecimal decimal4 = jdbcTemplate.queryForObject(sql, BigDecimal.class, id);

        BigDecimal decimal5 = jdbcTemplate.queryForObject(sql, BigDecimal.class, id);

        return jdbcTemplate.queryForObject(sql,BigDecimal.class,id);
    }


    public void addBook(Book book) {
        //1、添加图书SQL
        String sql = "insert into book(bookName,price,stock) values(?,?,?)";
        //2、执行添加
        jdbcTemplate.update(sql, book.getBookName(), book.getPrice(), book.getStock());
    }
    @Transactional(propagation = Propagation.REQUIRES_NEW)//结账炸了，库存不扣除
    public void updataBookStock(Integer id,Integer stock){
        //1、修改库存SQL
        String sql = "update book set stock = stock - ? where id = ?";
        //2..执行修改
        jdbcTemplate.update(sql,stock,id);
    }
    public void deleteBook(Integer id){
        //1、删除图书SQL
        String sql = "delete from book where id = ?";
        //2、执行删除
        jdbcTemplate.update(sql,id);
    }
}
